import { ref, nextTick, onMounted, onUnmounted, type Ref } from 'vue'

// 菜单项类型
export interface ContextMenuItem {
  id: string
  label: string
  icon?: string
  disabled?: boolean
  separator?: boolean
  children?: ContextMenuItem[]
  handler?: (item: ContextMenuItem, context?: any) => void
  shortcut?: string
  visible?: boolean
}

// 菜单位置
export interface MenuPosition {
  x: number
  y: number
}

// 上下文信息
export interface MenuContext {
  element: HTMLElement
  data?: any
  position: MenuPosition
}

// 右键菜单管理器
class ContextMenuManager {
  private activeMenu: {
    items: ContextMenuItem[]
    position: MenuPosition
    context?: any
  } | null = null
  
  private menuElement: HTMLElement | null = null
  private isVisible = false
  private listeners: Array<() => void> = []

  constructor() {
    this.handleDocumentClick = this.handleDocumentClick.bind(this)
    this.handleDocumentKeydown = this.handleDocumentKeydown.bind(this)
    this.handleWindowResize = this.handleWindowResize.bind(this)
  }

  /**
   * 显示右键菜单
   */
  show(items: ContextMenuItem[], position: MenuPosition, context?: any): void {
    this.hide() // 先隐藏现有菜单

    this.activeMenu = {
      items: items.filter(item => item.visible !== false),
      position: this.adjustPosition(position),
      context
    }

    this.isVisible = true
    this.addEventListeners()
    this.createMenuElement()
  }

  /**
   * 隐藏右键菜单
   */
  hide(): void {
    if (!this.isVisible) return

    this.isVisible = false
    this.activeMenu = null
    this.removeEventListeners()
    this.destroyMenuElement()
  }

  /**
   * 检查菜单是否可见
   */
  get visible(): boolean {
    return this.isVisible
  }

  /**
   * 获取当前菜单
   */
  get currentMenu() {
    return this.activeMenu
  }

  /**
   * 调整菜单位置，确保不超出视窗
   */
  private adjustPosition(position: MenuPosition): MenuPosition {
    const menuWidth = 200 // 预估菜单宽度
    const menuHeight = 300 // 预估菜单高度
    const padding = 10

    const adjustedPosition = { ...position }

    // 调整水平位置
    if (position.x + menuWidth > window.innerWidth - padding) {
      adjustedPosition.x = Math.max(padding, window.innerWidth - menuWidth - padding)
    }

    // 调整垂直位置
    if (position.y + menuHeight > window.innerHeight - padding) {
      adjustedPosition.y = Math.max(padding, window.innerHeight - menuHeight - padding)
    }

    return adjustedPosition
  }

  /**
   * 创建菜单DOM元素
   */
  private createMenuElement(): void {
    if (!this.activeMenu) return

    this.menuElement = document.createElement('div')
    this.menuElement.className = 'context-menu'
    this.menuElement.style.cssText = `
      position: fixed;
      top: ${this.activeMenu.position.y}px;
      left: ${this.activeMenu.position.x}px;
      z-index: 9999;
      background: var(--el-bg-color-overlay);
      border: 1px solid var(--el-border-color);
      border-radius: 6px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      padding: 6px 0;
      min-width: 160px;
      max-width: 240px;
      font-size: 14px;
      user-select: none;
    `

    this.renderMenuItems(this.activeMenu.items, this.menuElement)
    document.body.appendChild(this.menuElement)
  }

  /**
   * 渲染菜单项
   */
  private renderMenuItems(items: ContextMenuItem[], container: HTMLElement): void {
    items.forEach(item => {
      if (item.separator) {
        const separator = document.createElement('div')
        separator.className = 'context-menu-separator'
        separator.style.cssText = `
          height: 1px;
          background: var(--el-border-color-lighter);
          margin: 6px 12px;
        `
        container.appendChild(separator)
        return
      }

      const menuItem = document.createElement('div')
      menuItem.className = 'context-menu-item'
      menuItem.style.cssText = `
        padding: 8px 16px;
        cursor: ${item.disabled ? 'not-allowed' : 'pointer'};
        display: flex;
        align-items: center;
        justify-content: space-between;
        transition: background-color 0.2s;
        opacity: ${item.disabled ? '0.5' : '1'};
      `

      if (!item.disabled) {
        menuItem.addEventListener('mouseenter', () => {
          menuItem.style.backgroundColor = 'var(--el-color-primary-light-9)'
        })
        
        menuItem.addEventListener('mouseleave', () => {
          menuItem.style.backgroundColor = 'transparent'
        })

        menuItem.addEventListener('click', (e) => {
          e.stopPropagation()
          if (item.handler) {
            item.handler(item, this.activeMenu?.context)
          }
          this.hide()
        })
      }

      // 创建标签内容
      const labelContainer = document.createElement('div')
      labelContainer.style.cssText = 'display: flex; align-items: center; gap: 8px;'

      if (item.icon) {
        const icon = document.createElement('i')
        icon.className = item.icon
        icon.style.cssText = 'font-size: 16px; color: var(--el-text-color-regular);'
        labelContainer.appendChild(icon)
      }

      const label = document.createElement('span')
      label.textContent = item.label
      label.style.cssText = 'color: var(--el-text-color-primary);'
      labelContainer.appendChild(label)

      menuItem.appendChild(labelContainer)

      // 添加快捷键显示
      if (item.shortcut) {
        const shortcut = document.createElement('span')
        shortcut.textContent = item.shortcut
        shortcut.style.cssText = `
          color: var(--el-text-color-placeholder);
          font-size: 12px;
          margin-left: 16px;
        `
        menuItem.appendChild(shortcut)
      }

      container.appendChild(menuItem)

      // 处理子菜单（简化实现，暂不支持多级菜单）
      if (item.children && item.children.length > 0) {
        // 可以在这里添加子菜单支持
      }
    })
  }

  /**
   * 销毁菜单DOM元素
   */
  private destroyMenuElement(): void {
    if (this.menuElement && this.menuElement.parentNode) {
      this.menuElement.parentNode.removeChild(this.menuElement)
      this.menuElement = null
    }
  }

  /**
   * 添加事件监听器
   */
  private addEventListeners(): void {
    document.addEventListener('click', this.handleDocumentClick)
    document.addEventListener('keydown', this.handleDocumentKeydown)
    window.addEventListener('resize', this.handleWindowResize)
  }

  /**
   * 移除事件监听器
   */
  private removeEventListeners(): void {
    document.removeEventListener('click', this.handleDocumentClick)
    document.removeEventListener('keydown', this.handleDocumentKeydown)
    window.removeEventListener('resize', this.handleWindowResize)
  }

  /**
   * 处理文档点击事件
   */
  private handleDocumentClick(event: MouseEvent): void {
    if (!this.menuElement?.contains(event.target as Node)) {
      this.hide()
    }
  }

  /**
   * 处理键盘事件
   */
  private handleDocumentKeydown(event: KeyboardEvent): void {
    if (event.key === 'Escape') {
      this.hide()
    }
  }

  /**
   * 处理窗口大小变化
   */
  private handleWindowResize(): void {
    this.hide()
  }
}

// 全局右键菜单管理器实例
const globalContextMenuManager = new ContextMenuManager()

// 组合式API
export const useContextMenu = () => {
  const isVisible = ref(false)
  const currentMenu = ref<ContextMenuItem[]>([])

  const showMenu = (items: ContextMenuItem[], position: MenuPosition, context?: any) => {
    globalContextMenuManager.show(items, position, context)
    isVisible.value = true
    currentMenu.value = items
  }

  const hideMenu = () => {
    globalContextMenuManager.hide()
    isVisible.value = false
    currentMenu.value = []
  }

  return {
    isVisible,
    currentMenu,
    showMenu,
    hideMenu
  }
}

// 元素右键菜单Hook
export const useElementContextMenu = (
  element: Ref<HTMLElement | undefined>,
  menuItems: Ref<ContextMenuItem[]> | ContextMenuItem[] | (() => ContextMenuItem[])
) => {
  const { showMenu } = useContextMenu()

  const handleContextMenu = (event: MouseEvent) => {
    event.preventDefault()
    event.stopPropagation()

    const items = typeof menuItems === 'function' 
      ? menuItems() 
      : Array.isArray(menuItems) 
        ? menuItems 
        : menuItems.value

    if (items.length === 0) return

    showMenu(items, {
      x: event.clientX,
      y: event.clientY
    }, {
      element: event.target as HTMLElement,
      event
    })
  }

  onMounted(() => {
    if (element.value) {
      element.value.addEventListener('contextmenu', handleContextMenu)
    }
  })

  onUnmounted(() => {
    if (element.value) {
      element.value.removeEventListener('contextmenu', handleContextMenu)
    }
  })

  return {
    handleContextMenu
  }
}

// 预定义菜单项创建函数
export const createMessageContextMenu = (handlers: {
  copy?: () => void
  edit?: () => void
  delete?: () => void
  retry?: () => void
  save?: () => void
}) => {
  const items: ContextMenuItem[] = []

  if (handlers.copy) {
    items.push({
      id: 'copy',
      label: '复制',
      icon: 'el-icon-copy-document',
      handler: handlers.copy,
      shortcut: 'Ctrl+C'
    })
  }

  if (handlers.edit) {
    items.push({
      id: 'edit',
      label: '编辑',
      icon: 'el-icon-edit',
      handler: handlers.edit
    })
  }

  if (handlers.retry) {
    items.push({
      id: 'retry',
      label: '重新生成',
      icon: 'el-icon-refresh',
      handler: handlers.retry
    })
  }

  if (handlers.save) {
    items.push({
      id: 'save',
      label: '保存',
      icon: 'el-icon-download',
      handler: handlers.save,
      shortcut: 'Ctrl+S'
    })
  }

  if (handlers.delete) {
    items.push(
      { id: 'separator-1', label: '', separator: true },
      {
        id: 'delete',
        label: '删除',
        icon: 'el-icon-delete',
        handler: handlers.delete
      }
    )
  }

  return items
}

export const createTaskContextMenu = (handlers: {
  edit?: () => void
  duplicate?: () => void
  moveUp?: () => void
  moveDown?: () => void
  delete?: () => void
}) => {
  const items: ContextMenuItem[] = []

  if (handlers.edit) {
    items.push({
      id: 'edit',
      label: '编辑任务',
      icon: 'el-icon-edit',
      handler: handlers.edit
    })
  }

  if (handlers.duplicate) {
    items.push({
      id: 'duplicate',
      label: '复制任务',
      icon: 'el-icon-copy-document',
      handler: handlers.duplicate
    })
  }

  if (handlers.moveUp || handlers.moveDown) {
    items.push({ id: 'separator-1', label: '', separator: true })
    
    if (handlers.moveUp) {
      items.push({
        id: 'move-up',
        label: '上移',
        icon: 'el-icon-top',
        handler: handlers.moveUp
      })
    }

    if (handlers.moveDown) {
      items.push({
        id: 'move-down',
        label: '下移',
        icon: 'el-icon-bottom',
        handler: handlers.moveDown
      })
    }
  }

  if (handlers.delete) {
    items.push(
      { id: 'separator-2', label: '', separator: true },
      {
        id: 'delete',
        label: '删除任务',
        icon: 'el-icon-delete',
        handler: handlers.delete
      }
    )
  }

  return items
}

export default globalContextMenuManager